#include "StdAfx.h"
#include "SGFFile.h"


CSGFFile::CSGFFile(CString filePath)
{
	m_FilePath = filePath;
}


void CSGFFile::Init(void)
{
	ReadMoveOrder();
}


CSGFFile::~CSGFFile(void)
{
}


/*void CSGFFile::ReadMoveOrder(void)
{
	CFile SGFFile(m_FilePath, CFile::modeRead);
	char buffer[4];
	int num = 0;
	while (SGFFile.Read(buffer, 2)) {
		if (buffer[0] == 'A' && buffer[1] == 'B') {
			while (SGFFile.Read(buffer, 4) && buffer[0] != ';') {
				int8_t x = buffer[1] - 'a';
				int8_t y = buffer[2] - 'a';
				SLocationOnGoBoard location = {x, y};
				TRACE("%d, %d\n", x, y);
				m_RangziVector.push_back(location);
			}
			break;
		}
		SGFFile.Seek(-1, CFile::current);
	}
	SGFFile.Seek(0, CFile::begin);

	while (SGFFile.Read(buffer, 1)) {
		if (buffer[0] == ';') {
			SGFFile.Read(buffer, 1);

			if (buffer[0] != 'B' && buffer[0] != 'W') continue;

			char color = buffer[0];
			SGFFile.Read(buffer, 4);

			if (buffer[1] == ']') return;

			int8_t x = buffer[1] - 'a';
			int8_t y = buffer[2] - 'a';
			SLocationOnGoBoard location = {x, y};
			m_MoveOrder.push_back(location);
			if (color == 'B') {
				m_ColorOrder.push_back(BLACK_COLOR);
			} else {
				m_ColorOrder.push_back(WHITE_COLOR);
			}
		}
	}

	SGFFile.Close();
}*/


void CSGFFile::ReadMoveOrder()
{
	CStdioFile SGFFile;
	SGFFile.Open(m_FilePath, CFile::modeRead);
	CString contentStr;
	CString buffer;
	while (SGFFile.ReadString(buffer)) {
		contentStr += buffer;
	}
	int length = contentStr.GetLength();
	TRACE("length = %d", length);
	for (int i=0; i<length-1; i++) {
		if (contentStr.Mid(i, 2) == CString("AB")) {
			for (int j=i+2; contentStr[j]!=';'; j+=4) {
				int8_t x = contentStr[j + 1] - 'a';
				int8_t y = contentStr[j + 2] - 'a';
				SLocationOnGoBoard location = {x, y};
				m_RangziVector.push_back(location);
			}
			break;
		}
	}
	for (int i=0; i<length; i++) {
		if (contentStr[i] == ';') {
			if (contentStr[i + 1] != 'B' && contentStr[i + 1] != 'W') continue;
			wchar_t color = contentStr[i + 1];
			if (contentStr[i + 3] == ']') return;
			int8_t x = contentStr[i + 3] - 'a';
			int8_t y = contentStr[i + 4] - 'a';
			SLocationOnGoBoard location = {x, y};
			m_MoveOrder.push_back(location);
			if (color == 'B') {
				m_ColorOrder.push_back(BLACK_COLOR);
			} else {
				m_ColorOrder.push_back(WHITE_COLOR);
			}
		}
	}
	SGFFile.Close();
}


void CSGFFile::CopyMoveOrder(TLocationVector *dest) const
{
	*dest = m_MoveOrder;
}


void CSGFFile::CopyColorOrder(TColorVector *dest) const
{
	*dest = m_ColorOrder;
}


void CSGFFile::CopyRangziVector(TLocationVector *dest) const
{
	*dest = m_RangziVector;
}